package com.lqk.java;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author liqiankun
 * @date 2022/11/8 19:01
 * @description 了解类的加载器
 **/
public class ClassLoaderTest {
    @Test
    public void test1(){
        // 对于自定义类, 使用系统类加载器进行加载
        ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
        System.out.println(classLoader);
        // 调用系统类加载器的getParent(): 获取扩展类加载器
        ClassLoader parent = classLoader.getParent();
        System.out.println(parent);
        // 调用扩展类加载器的getParent(): 获取引导类加载器
        // 引导类加载器主要负责加载java的核心类库, 无法加载自定义类的
        ClassLoader parent1 = parent.getParent();
        System.out.println(parent1);

        // 由引导类加载器加载到内存中
        ClassLoader classLoader1 = String.class.getClassLoader();
        System.out.println(classLoader1);
    }

    /**
     * Properties: 用来读取配置文件
     */
    @Test
    public void test2() throws Exception {
        Properties props = new Properties();
        // 此时的文件默认在当前的module下
        // 读取配置文件方式一
        long start1 = System.currentTimeMillis();
//        FileInputStream fis = new FileInputStream("jdbc.properties");
        FileInputStream fis = new FileInputStream("src/jdbc1.properties");
        props.load(fis);
        System.out.println(System.currentTimeMillis()-start1);

        String user = props.getProperty("user");
        String password = props.getProperty("password");
        System.out.println("user = "+user+", password = " +password);

        // 读取配置文件方式二: 使用classLoader
        // 配置文件默认识别为: 当前module的src下
        long start2 = System.currentTimeMillis();
        ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("jdbc1.properties");
        props.load(is);
        System.out.println(System.currentTimeMillis()-start2);

        String user2 = props.getProperty("user");
        String password2 = props.getProperty("password");
        System.out.println("user = "+user2+", password = " +password2);

    }
}
